package com.sky.controller.user;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.AddressBookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
@Api(tags = "C端-地址簿相关接口")
@RequestMapping("/user/addressBook")
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;

    @ApiOperation("查询登录用户所有地址")
    @GetMapping("/list")
    public Result<List<AddressBook>> list(){
        AddressBook addressBook = new AddressBook();
        addressBook.setId(BaseContext.getCurrentId());
        List<AddressBook> list = addressBookService.list(addressBook);
        return Result.success(list);
    }

    @ApiOperation("新增地址")
    @PostMapping
    public Result save(@RequestBody AddressBook addressBook){
        log.info("新增地址:{}",addressBook);
        addressBookService.save(addressBook);
        return Result.success();
    }

    @ApiOperation("查询默认地址")
    @GetMapping("/default")
    public Result defaultAddress(){
        log.info("查询默认地址");
        AddressBook addressBooK = new AddressBook();
        addressBooK.setIsDefault(1);
        addressBooK.setId(BaseContext.getCurrentId());

        List<AddressBook> list = addressBookService.list(addressBooK);
        if(list!=null&&list.size()==1){
            return Result.success(list.get(0));
        }
        return Result.error("没有找到默认地址");
    }

    @ApiOperation("根据ID查询地址")
    @GetMapping("/{id}")
    public Result<AddressBook> getById(@PathVariable Long id){
        log.info("根据ID查询地址:{}",id);
        AddressBook addressBook = addressBookService.getById(id);
        return Result.success(addressBook);
    }

    @ApiOperation("修改地址")
    @PutMapping
    public Result update(@RequestBody AddressBook addressBook){
        log.info("修改地址:{}",addressBook);
        addressBookService.update(addressBook);
        return Result.success();
    }

    @ApiOperation("设置默认地址")
    @PutMapping("/default")
    public Result setDefalut(@RequestBody AddressBook addressBook){
        log.info("设置默认地址:{}",addressBook);
        addressBookService.setDefalut(addressBook);
        return Result.success();
    }

    @ApiOperation("根据ID删除地址")
    @DeleteMapping
    public Result deleteById(Long id){
        addressBookService.deleteById(id);
        return Result.success();
    }
}
